﻿/*
 *Copyright (c) 2014, Riccardo Cagnasso
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

using PasslibNet.Algorithms;
using PasslibNet.Utils;

namespace PasslibNet
{
    /// <summary>
    /// Passlib is a simple class that lets you Encrypt and Verify password
    /// Encrypt uses one of the available alghoritms (currently Sha512)
    /// Verify will verify the password using the proper algorithm
    /// </summary>
    public static class Passlib
    {
        /// <summary>
        /// Encrpyt a password using a safe algorithm (currently Sha512)
        /// </summary>
        /// 
        /// <param name="secret">The password to be hashed</param>
        /// 
        /// <returns>An hash in Modular Crypt Format</returns>
        public static string Encrypt(string secret)
        {
            var encoder = new Sha512();
            return encoder.Encrypt(secret);
        }

        /// <summary>
        /// Veryfies a password against a given MCF hash
        /// The hash will be parsed in order to choose the proper algorithm
        /// according to the MCF non-standard.
        /// </summary>
        /// <param name="secret">The password to be verified</param>
        /// <param name="hash">A MCF hash that will be used to verify the password</param>
        /// <returns>true if the password is correct, false otherwise</returns>
        public static bool Verify(string secret, string hash)
        {
            var algo = ModularCryptFormat.Factory(hash, initialize:true);

            return algo.Verify(secret, hash);
        }
    }
}
